import { useCallback, useEffect, useState } from 'react';
import { BigNumber } from 'ethers';
import useBasisCash from './useBasisCash';
import config from '../config';
import { ethers } from 'ethers';

const useTreasuryAmount = () => {
  const [amount, setAmount] = useState('0');
  const basisCash = useBasisCash();

  const fetchBalance = useCallback(async () => {
    const amt = await basisCash.externalTokens[config.spConfigs['s' + config.group.toUpperCase()]].displayedBalanceOf(config.externalTokens['Fund'][0]);
    console.log('useTreasuryAmount', amt);
    setAmount(amt);
  }, [basisCash, basisCash?.isUnlocked, config.group]);

  useEffect(() => {
    if (basisCash?.isUnlocked) {
      fetchBalance().catch(err => console.error('useTreasuryAmount', err.stack));

      const refreshBalance = setInterval(fetchBalance, config.refreshInterval);
      return () => clearInterval(refreshBalance);
    }
  }, [basisCash, basisCash?.isUnlocked, config.group, setAmount]);
  return amount;
};

export default useTreasuryAmount;
